import json
from urllib import request
from urllib.parse import urlencode


def post_req(url, headers, req_body, parm=None):
    if parm is not None:
        url = url + '?' + urlencode(parm)
    data = bytes(json.dumps(req_body), encoding='utf8')
    req = request.Request(url=url, data=data, headers=headers, method='POST')
    try:
        response = request.urlopen(req)
    except Exception as e:
        print(e.read().decode())
        return {}
    
    rsp_body = response.read().decode('utf-8')
    rsp_dict = json.loads(rsp_body)
    return rsp_dict


def get_req(url, headers, parm=None):
    if parm is not None:
        url = url + '?' + urlencode(parm)
    print(url)
    req = request.Request(url=url, headers=headers, method='GET')
    try:
        response = request.urlopen(req)
    except Exception as e:
        print(e.read().decode())
        return {}
    
    rsp_body = response.read().decode('utf-8')
    rsp_dict = json.loads(rsp_body)
    return rsp_dict


def patch_req(url, headers, req_body, parm=None):
    if parm is not None:
        url = url + '?' + urlencode(parm)
    data = bytes(json.dumps(req_body), encoding='utf8')
    req = request.Request(url=url, data=data, headers=headers, method='PATCH')
    try:
        response = request.urlopen(req)
    except Exception as e:
        print(e.read().decode())
        return {}
    
    rsp_body = response.read().decode('utf-8')
    rsp_dict = json.loads(rsp_body)
    return rsp_dict